#!/usr/local/bin/python
# -*- coding: utf-8 -*-


import json
from datetime import datetime

from PyQt5 import QtWidgets
from PyQt5.QtCore import QDate, Qt, QThread, pyqtSignal, QDateTime
from PyQt5.QtWidgets import QAbstractItemView, QTableWidgetItem, QTreeWidgetItem, QMessageBox, QMenu, QWidget
from dateutil.relativedelta import relativedelta
from xToolkit.xstring import xstring

import ConfigManage
import VoucherDataCheck
from AccountBook import AccountBook
from BalanceSheet import BalanceSheet
from IncomeStatement import IncomeStatement
from data_alchemy.account_voucher_alchemy import AccountVoucherAlchemy
import init
import toolkit
from data_alchemy.investment_flow_alchemy import InvestmentFlowAlchemy
from initLogger import logger
import initVoucherPage
from initXirrPage import FLOW_TYPE_DING_TOU

#from ui.AccountVoucherUI import Ui_AccountVoucher
from ui.AccountVoucherUI_relative_layout_a import Ui_AccountVoucher


class AccountVoucherWidget(QWidget, Ui_AccountVoucher):
    def __init__(self):
        super(AccountVoucherWidget, self).__init__()




        self.currentVoucherTextEdit = None
        self.currentDate = datetime.now()  #记录当前事件
        self.targetDate = self.currentDate  - relativedelta(days=init.GO_DAYS)#记录当前系统查看数据的时间
        self.xuhaoNo = 0     #在当前表格中的序号
        self.bianhaoID = 0   #数据所处的编号

        self.accountVoucherResult = None #用于存储记账凭证的结果


        self.setupUi(self)
        self.initAccountVoucherUI()




   ###########################################################################
    # 记账凭证页面处理
    #
    ###########################################################################

    def initAccountVoucherUI(self):
        '''
        函数功能：对记账凭证UI窗口进行初始化
        :return:
        '''
        #self.change_date_calendarWidget.setVisible(False)  # 设置日历控件不可见
        #初始化日期编辑控件
        self.date_dateEdit.setCalendarPopup(True)
        #self.date_dateEdit.setDate(QDate.currentDate())
        self.date_dateEdit.setDate(self.targetDate)

        #初始化表格控件
        self.initVoucherTableUI()  #初始化记账凭证数据表控件UI
        self.initVoucherTableData()  #初始化记账凭证表控件数据

        #初始化页面标题
        self.initAccountVoucherTitleUI()

        #初始化查询模块相关控件
        self.year_comboBox.addItems(init.YEAR_NAME_LIST)
        self.month_comboBox.addItems(init.MONTH_NAME_LIST)
        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

        #记账凭证输入框控件初始化
        self.property_increase_name_textEdit.setReadOnly(True)
        self.property_decrease_name_textEdit.setReadOnly(True)
        self.ownership_increase_name_textEdit.setReadOnly(True)
        self.ownership_decrease_name_textEdit.setReadOnly(True)

        #初始化凭证科目树控件
        self.initVoucherTree()

    def initVoucherTableUI(self):
        '''
        函数功能：对记账凭证表进行初始化
        :return:
        '''

        self.voucher_tableWidget.setRowCount(initVoucherPage.VOUCHER_TABLE_ROW_COUNT)  #设置行数目
        self.voucher_tableWidget.setColumnCount(initVoucherPage.VOUCHER_TABLE_COLUMN_COUNT)  #设置列数目
        self.voucher_tableWidget.setHorizontalHeaderLabels(initVoucherPage.VOUCHER_TABLE_COLUMN_CONTEXT) #设置列名

        self.voucher_tableWidget.resizeRowsToContents()    #设置行宽自适应
        #self.voucher_tableWidget.resizeColumnsToContents()  #设置列宽自适应
        self.voucher_tableWidget.setShowGrid(True)  #设置显示网络线
        self.voucher_tableWidget.setAlternatingRowColors(True) #设置表格颜色交错显示
        self.voucher_tableWidget.verticalHeader().setVisible(False)  #隐藏垂直标题
        self.voucher_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.voucher_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)   #设置选中整行
        self.voucher_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格


        self.voucher_tableWidget.setColumnWidth(0, 75)
        self.voucher_tableWidget.setColumnWidth(1, 75)
        self.voucher_tableWidget.setColumnWidth(2, 400)
        self.voucher_tableWidget.setColumnWidth(3, 150)
        self.voucher_tableWidget.setColumnWidth(4, 150)
        self.voucher_tableWidget.setColumnWidth(5, 550)

    def initVoucherTree(self):
        '''
        对凭证科目信息进行初始化
        :return:
        '''

        self.showVoucherTreeInfo(ConfigManage.readConfig("PROPERTY_NAME_JSON"))

    def initAccountVoucherTitleUI(self):
        '''
        函数功能:初始化页面标题
        :return:
        '''
        accountVoucherTitleStr="%d年%d月记账凭证"%(self.targetDate.year, self.targetDate.month)
        self.title_label.setText(accountVoucherTitleStr)

    def showVoucherTreeInfo(self, subjectJsonTree):
        '''
        函数功能：展示指定的科目信息数据树
        :param subjectJsonTree:
        :return:
        '''

        self.subject_treeWidget.clear()
        self.subject_treeWidget.setColumnCount(1)
        self.subject_treeWidget.setItemsExpandable(True)
        logger.debug(subjectJsonTree)
        treeContextInfo = json.loads(subjectJsonTree)
        logger.debug(treeContextInfo)
        for key in treeContextInfo.keys():
            rootTreeWidgetItem = QTreeWidgetItem(self.subject_treeWidget)
            rootTreeWidgetItem.setText(0, key)
            if treeContextInfo[key] != "":
                self.parseVoucherTree(treeContextInfo[key], rootTreeWidgetItem)
            self.subject_treeWidget.addTopLevelItem(rootTreeWidgetItem)
            #end for

        self.subject_treeWidget.expandAll()

    def parseVoucherTree(self, dataDic, treeWidgetItem):
        '''
        将json数据结构映射到树形控件中
        :param dataDic:
        :param rootTreeWidgetItem:
        :return:
        '''

        for key in  dataDic.keys():
            oneTreeWidgetItem = QTreeWidgetItem(treeWidgetItem)
            oneTreeWidgetItem.setText(0, key)
            if dataDic[key]!="":
                self.parseVoucherTree(dataDic[key], oneTreeWidgetItem)


    def clearTableContext(self):
        '''
        对记账凭证中表格中的内容进行清空
        :return:
        '''
        self.voucher_tableWidget.clear()
        self.voucher_tableWidget.setHorizontalHeaderLabels(initVoucherPage.VOUCHER_TABLE_COLUMN_CONTEXT)

    def showVoucherTableAsync(self, year, month):
        '''
        函数功能：以异步形式展示记账凭证
        :param year:
        :param month:
        :return:
        '''

        self.search_pushButton.setEnabled(False)

        logger.debug("call showVoucherTableAsync function start ")
        startDateStr, endDateStr = toolkit.monthlyChange(year, month)
        accountVoucher = AccountVoucherAlchemy()

        logger.debug("call showVoucherTable function sql data start ")
        self.accountVoucherResult = accountVoucher.SearchVoucherByDate(startDateStr, endDateStr)

        logger.debug("call showVoucherTable function sql data end ")
        accountVoucherResultLen = len(self.accountVoucherResult)

        #根据数据实际数量，对表格的行数进行重新设置
        self.voucher_tableWidget.setRowCount(accountVoucherResultLen)
        self.voucher_tableWidget.scrollToTop()
        if accountVoucherResultLen% initVoucherPage.ONE_THREAD_DATA ==0:
            threadCount = int(accountVoucherResultLen/initVoucherPage.ONE_THREAD_DATA)
        else:
            threadCount = int(accountVoucherResultLen/initVoucherPage.ONE_THREAD_DATA) + 1

        if threadCount == 0:
            self.search_pushButton.setEnabled(True)
        else:
            self.updateVoucherTableThread = UpdateVoucherTableThread(threadCount)
            self.updateVoucherTableThread.send_signal.connect(self.updateVoucherTableData)
            self.updateVoucherTableThread.start()



    def showVoucherTableSync(self, year, month):
        '''
        函数功能：以同步方式展示记账凭证
        :param year:
        :param month:
        :return:
        '''

        logger.debug("call showVoucherTable function start ")
        startDateStr, endDateStr = toolkit.monthlyChange(year, month)
        accountVoucher = AccountVoucherAlchemy()

        logger.debug("call showVoucherTable function sql data start ")
        result = accountVoucher.SearchVoucherByDate(startDateStr, endDateStr)

        logger.debug("call showVoucherTable function sql data end ")
        talbeRealLen = len(result)



        #根据数据实际数量，对表格的行数进行重新设置
        self.voucher_tableWidget.setRowCount(talbeRealLen)

        logger.debug("call showVoucherTable function show data start ")
        for i in range(len(result)):
            logger.debug("记账凭证展示第 %d 项数据 "%(i))
            dataRow = result[i]

            #序号
            noStr = "%d\t" % (i + 1)
            noItem = QTableWidgetItem(noStr)
            self.voucher_tableWidget.setItem(i, 0, noItem)

            #编号
            serialNumberStr = str(dataRow.id)
            serialNumberItem = QTableWidgetItem(serialNumberStr)
            self.voucher_tableWidget.setItem(i, 1, serialNumberItem)

            # 摘要
            summaryItem = QTableWidgetItem(dataRow.summary)
            self.voucher_tableWidget.setItem(i, 2, summaryItem)


            # 日期
            accountDateStr = str(dataRow.account_date)
            accountDateItem = QTableWidgetItem(accountDateStr)
            self.voucher_tableWidget.setItem(i, 3, accountDateItem)

            # 金额
            if dataRow.property_increase_value != 0:
                moneyValue = dataRow.property_increase_value
            elif dataRow.property_decrease_value != 0:
                moneyValue = dataRow.property_decrease_value
            elif dataRow.ownership_increase_value != 0:
                moneyValue = dataRow.ownership_increase_value
            else:
                moneyValue = dataRow.ownership_decrease_value

            moneyValueStr = xstring.dispose(toolkit.processValueSignificant(moneyValue)).humanized_amount(complex=True)
            moneyValueWiggetItem = QTableWidgetItem(moneyValueStr)
            self.voucher_tableWidget.setItem(i, 4, moneyValueWiggetItem)

            # 详情
            detailContext = ""
            if dataRow.property_increase_name != "":
                if detailContext != "":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "资产增加：%s" % (dataRow.property_increase_name)
            if dataRow.property_decrease_name != "":
                if detailContext != "":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "资产减少：%s" % (dataRow.property_decrease_name)
            if dataRow.ownership_increase_name != "":
                if detailContext != "":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "权属增加：%s" % (dataRow.ownership_increase_name)
            if dataRow.ownership_decrease_name != "":
                if detailContext != "":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "权属减少：%s" % (dataRow.ownership_decrease_name)

            detailContextWiggetItem = QTableWidgetItem(detailContext)
            self.voucher_tableWidget.setItem(i, 5, detailContextWiggetItem)


        self.voucher_tableWidget.resizeRowsToContents()  # 设置行宽自适应

        logger.debug("call showVoucherTable function  end ")


    def initVoucherTableData(self):
        '''
        函数功能：对表格进行数据初始化
        :return:
        '''
        logger.debug("search_pushButton.setEnabled(False)")


        #self.search_pushButton.setEnabled(False)
        #self.showVoucherTableAsync(self.targetDate.year, self.targetDate.month)


        self.showVoucherTableSync(self.targetDate.year, self.targetDate.month)

    def deleteVoucherAccount(self, rowNum):
        '''
        函数功能：处理删除记账凭证菜单
        :return:
        '''
        voucherAccoutID = self.voucher_tableWidget.item(rowNum, 1).text()
        accountVoucherAlchemy = AccountVoucherAlchemy()
        logger.debug("id=%s"%voucherAccoutID)
        accountVoucherAlchemy.DelVoucherItem(voucherAccoutID)
        self.clearTableContext()
        self.showVoucherTableSync(self.targetDate.year, self.targetDate.month)


    def modifyVoucherAccount(self, rowNum):
        '''
        函数功能：处理修改记账凭证菜单
        :param rowNum:
        :return:
        '''

        #获取待修改数据的序号
        self.xuhaoNo = int(self.voucher_tableWidget.item(rowNum, 0).text())

        #获取待修改数据的记账凭证编号信息
        self.bianhaoID = int(self.voucher_tableWidget.item(rowNum, 1).text())
        accountingVoucher = AccountVoucherAlchemy()
        voucherAccountInfo = accountingVoucher.SearchVoucheByID(self.bianhaoID)


        #记账凭证摘要信息
        summaryText = voucherAccountInfo.summary
        self.summary_textEdit.setText(summaryText)

        #记账凭证日期信息
        targetDatetime = voucherAccountInfo.account_date
        self.date_dateEdit.setDate(targetDatetime)


        #资产增加名称信息
        propertyIncreaseName = voucherAccountInfo.property_increase_name
        self.property_increase_name_textEdit.setText(propertyIncreaseName)

        #资产增加金额
        propertyIncreaseValue = voucherAccountInfo.property_increase_value
        propertyIncreaseValueStr = xstring.dispose(toolkit.processValueSignificant(propertyIncreaseValue)).humanized_amount(complex=True)
        self.property_increase_value_lineEdit.setText(propertyIncreaseValueStr)

        #资产减少名称信息
        propertyDecreaseName = voucherAccountInfo.property_decrease_name
        self.property_decrease_name_textEdit.setText(propertyDecreaseName)

        #资产减少金额
        propertyDecreaseValue = voucherAccountInfo.property_decrease_value
        propertyDecreaseValueStr = xstring.dispose(toolkit.processValueSignificant(propertyDecreaseValue)).humanized_amount(complex=True)
        self.property_decrease_value_lineEdit.setText(propertyDecreaseValueStr)

        #权属增加名称信息
        ownershipIncreaseName = voucherAccountInfo.ownership_increase_name
        self.ownership_increase_name_textEdit.setText(ownershipIncreaseName)


        #权属增加金额
        ownershipIncreaseValue = voucherAccountInfo.ownership_increase_value
        ownershipIncreaseValueStr = xstring.dispose(toolkit.processValueSignificant(ownershipIncreaseValue)).humanized_amount(complex=True)
        self.ownership_increase_value_lineEdit.setText(ownershipIncreaseValueStr)

        #权属减少名称信息
        ownershipDecreaseName = voucherAccountInfo.ownership_decrease_name
        self.ownership_decrease_name_textEdit.setText(ownershipDecreaseName)

        #权属减少金额
        ownershipDecreaseValue = voucherAccountInfo.ownership_decrease_value
        ownershipDecreaseValueStr = xstring.dispose(toolkit.processValueSignificant(ownershipDecreaseValue)).humanized_amount(complex=True)
        self.ownership_decrease_value_lineEdit.setText(ownershipDecreaseValueStr)


        self.add_pushButton.setText(initVoucherPage.MODIFY_BUTTON)





    def onClickTree(self, index):
        '''
        响应树形控件响应时间
        :return:
        '''

        #item = self.treeWidget.currentItem()
        #logger.debug("index=%d",index)
        #logger.debug(item.text(0))

    def onItemDoubleClicked(self, item, column):
        '''
        响应树形控件双击事件
        :return:
        '''

        currentItem = item
        fullPath = currentItem.text(0)
        while(currentItem.parent()!=None):
            currentItem = currentItem.parent()
            fullPath = currentItem.text(0) + "->" + fullPath
        logger.debug(fullPath)

        if self.currentVoucherTextEdit!=None:
            self.currentVoucherTextEdit.setText(fullPath)




    def onAddOneVoucher(self):
        '''
        函数功能：响应“添加一条记账凭证”的信号
        :return:
        '''

        #记账凭证摘要
        summary = self.summary_textEdit.toPlainText()
        #记账凭证时间
        voucherDateStr = self.date_dateEdit.text()
        voucherDate = datetime.strptime(voucherDateStr, '%Y/%m/%d')

        #资产增加
        propertyIncreaseName = self.property_increase_name_textEdit.toPlainText()
        propertyIncreaseValue = self.property_increase_value_lineEdit.text()
        if(propertyIncreaseValue=='') :
            propertyIncreaseFloat = 0.0
        else:
            propertyIncreaseFloat = float(propertyIncreaseValue.replace(",",""))

        #资产减少
        propertyDecreaseName = self.property_decrease_name_textEdit.toPlainText()
        propertyDecreaseValue = self.property_decrease_value_lineEdit.text()
        if(propertyDecreaseValue==''):
            propertyDecreaseFloat = 0.0
        else:
            propertyDecreaseFloat = float(propertyDecreaseValue.replace(",",""))

        #权属增加
        ownershipIncreaseName = self.ownership_increase_name_textEdit.toPlainText()
        ownershipIncreaseValue = self.ownership_increase_value_lineEdit.text()
        if (ownershipIncreaseValue==''):
            ownershipIncreaseFloat = 0.0
        else:
            ownershipIncreaseFloat = float(ownershipIncreaseValue.replace(",",""))

        #权属减少
        ownershipDecreaseName = self.ownership_decrease_name_textEdit.toPlainText()
        ownershipDecreaseValue = self.ownership_decrease_value_lineEdit.text()
        if(ownershipDecreaseValue==''):
            ownershipDecreaseFloat = 0.0
        else:
            ownershipDecreaseFloat = float(ownershipDecreaseValue.replace(",",""))

        #对数据合法性进行检查
        result,message = VoucherDataCheck.CheckVoucherData( propertyIncreaseName,
                                                            propertyIncreaseFloat,
                                                            propertyDecreaseName,
                                                            propertyDecreaseFloat,
                                                            ownershipIncreaseName,
                                                            ownershipIncreaseFloat,
                                                            ownershipDecreaseName,
                                                            ownershipDecreaseFloat)

        if(result == False):
            #处理数据异常，添加失败
            QMessageBox.information(None, "【错误】添加失败", message, QMessageBox.Ok)
            return


        logger.debug("参数获取：\n"
              "摘要：%s \n"
              "日期：%s \n"
              "资产增加: %s=%.2f \n"
              "资产减少:%s=%.2f \n"
              "权属增加:%s=%.2f \n"
              "权属减少:%s=%.2f \n"%(summary, voucherDate.strftime("%Y-%m-%d"),
                                 propertyIncreaseName, propertyIncreaseFloat,
                               propertyDecreaseName, propertyDecreaseFloat,
                               ownershipIncreaseName, ownershipIncreaseFloat,
                               ownershipDecreaseName, ownershipDecreaseFloat))





        accountVoucher = AccountVoucherAlchemy(voucherDate,
                                               voucherNo="000",
                                               summary=summary,
                                               propertyIncreaseName=propertyIncreaseName,
                                               propertyIncreaseValue=propertyIncreaseFloat,
                                               propertyDecreaseName=propertyDecreaseName,
                                               propertyDecreaseValue=propertyDecreaseFloat,
                                               ownershipIncreaseName=ownershipIncreaseName,
                                               ownershipIncreaseValue=ownershipIncreaseFloat,
                                               ownershipDecreaseName=ownershipDecreaseName,
                                               ownershipDecreaseValue=ownershipDecreaseFloat
                                               )



        if (self.add_pushButton.text()=="添加"):
            accountVoucher.AddVoucherItem()
            self.AddInvestmentFlowItem(accountVoucher)  #添加投资数据流



        elif (self.add_pushButton.text()=="修改"):
            #修改记账凭证
            accountVoucher.ModifiyVoucherItem(self.bianhaoID)
            self.ModifiyInvestmentFlowItem(accountVoucher)


            self.add_pushButton.setText(initVoucherPage.ADD_BUTTON)

        #清除输入内容
        self.onClearCurVoucher()

        #新增当月的数据进行查询
        year = voucherDate.year
        yearIndex = year-init.FIRST_YEAR
        month = voucherDate.month
        monthIndex = month - 1

        self.year_comboBox.setCurrentIndex(yearIndex)
        self.month_comboBox.setCurrentIndex(monthIndex)
        self.onSearchVoucher()



    def ModifiyInvestmentFlowItem(self, investmentVoucherItem):
        '''
        函数功能：对已经添加的投资数据流进行修改
        :param investmentVoucherItem:
        :return:
        注：先执行删除操作，再执行添加操作，逻辑上可能更简单
        '''

        #
        investmentFlowAlchemy = InvestmentFlowAlchemy()
        investmentFlowResult = investmentFlowAlchemy.SearchInvestmentFlowByVoucherId(self.bianhaoID)
        if len(investmentFlowResult)<=0:
            #之前的投资数据流中，没有该记账凭证记录。修改后的记账凭证如果是投资行为，加入投资数据流中。
            investmentVoucherItem.id = self.bianhaoID
            self.AddInvestmentFlowItem(investmentVoucherItem)
            return True

        # 判断修改后的记账凭证是否是投资行为
        if (investmentVoucherItem.property_increase_value!=investmentVoucherItem.property_decrease_value):
            #资产增加值不等于资产减少值，不属于投资行为
            #不是投资行为，把原来的投资数据流记录删除#######
            for investmentFlowItem in investmentFlowResult:
                investmentFlowAlchemy.DelInvestmentFlowItem(investmentFlowItem.id)
            return False
        if (investmentVoucherItem.property_increase_name.find("资产->投资->理财")==-1 and \
           investmentVoucherItem.property_decrease_name.find("资产->投资->理财")==-1):
            # 不是投资行为，把原来的投资数据流记录删除#######
            for investmentFlowItem in investmentFlowResult:
                investmentFlowAlchemy.DelInvestmentFlowItem(investmentFlowItem.id)
            return False

        #是投资行为做修改操作#########

        subStringList = investmentVoucherItem.property_increase_name.split("->")
        substringListLen = len(subStringList)
        investmentName = subStringList[substringListLen - 1]
        investmentFlowAlchemy = InvestmentFlowAlchemy(investmentDate=investmentVoucherItem.account_date,
                                                      investmentValue=investmentVoucherItem.property_increase_value,
                                                      investmentPath=investmentVoucherItem.property_increase_name,
                                                      flowType=FLOW_TYPE_DING_TOU,
                                                      voucherId=investmentVoucherItem.id)

        for investmentFlowItem in investmentFlowResult:
            investmentFlowAlchemy.ModifiyInvestmentFlowItem(investmentFlowItem.id)

    def AddInvestmentFlowItem(self, investmentVoucherItem):
        '''
        函数功能：判断添加的记账凭证是否属于投资理财，如果属于投资理财，加入投资数据流记录InvestmentFlowAlchemy
        :return:
        '''

        if (investmentVoucherItem.property_increase_value!=investmentVoucherItem.property_decrease_value):
            #资产增加值不等于资产减少值，不属于投资行为
            return False
        if (investmentVoucherItem.property_increase_name.find("资产->投资->理财")!=-1 or \
           investmentVoucherItem.property_decrease_name.find("资产->投资->理财")!=-1):
            #资产增加或资产减少项中存在“资产->投资->理财”属性，的记账凭证属于投资行为，可以添加到投资数据流中
            subStringList = investmentVoucherItem.property_increase_name.split("->")
            substringListLen = len(subStringList)
            investmentName = subStringList[substringListLen-1]
            investmentFlowAlchemy = InvestmentFlowAlchemy(investmentDate = investmentVoucherItem.account_date,
                                                      investmentValue = investmentVoucherItem.property_increase_value,
                                                      investmentPath = investmentVoucherItem.property_increase_name,
                                                      flowType = FLOW_TYPE_DING_TOU,
                                                      voucherId = investmentVoucherItem.id)
            investmentFlowAlchemy.AddInvestmentItem()


    def onSearchVoucher(self):
        '''
        响应查询记账凭证消息
        :return:
        '''

        #启动数据展示功能，查询按钮暂时不可用



        year = int(self.year_comboBox.currentText())
        month = int(self.month_comboBox.currentText())
        self.targetDate = toolkit.setTargetDate(year, month)

        #设置记账凭证标题
        self.initAccountVoucherTitleUI()

        logger.debug("year=%d, month=%d" % (year, month))
        self.clearTableContext()

        #self.showVoucherTableAsync(year, month)
        self.showVoucherTableSync(year, month)


    def onGoLastMonth(self):
        """
        函数功能；展示上一个月的账簿数据
        :return:
        """


        self.targetDate = toolkit.getLastMonth(self.targetDate, number=1)
        logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))
        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

        self.initAccountVoucherTitleUI()  # 设置记账凭证标题
        self.clearTableContext()
        self.showVoucherTableSync(self.targetDate.year, self.targetDate.month)


    def onGoNextMonth(self):
        """
        函数功能；展示下一个月的账簿数据
        :return:
        """

        self.targetDate = toolkit.getNextMonth(self.targetDate, number=1)
        logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))

        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

        self.initAccountVoucherTitleUI()  # 设置记账凭证标题
        self.clearTableContext()
        self.showVoucherTableSync(self.targetDate.year, self.targetDate.month)


    def onUpdateAllDate(self):
        '''
        函数功能：更新当月全部数据
        :return:
        '''

        #更新账簿数据
        accountBook = AccountBook(self.targetDate.year, self.targetDate.month)
        accountBook.getInitAccountBookValue()
        accountBook.calculateAccountVoucherMonthly()
        accountBook.genAccountBook()

        #更新资产负债表数据
        blanceSheet = BalanceSheet(self.targetDate.year, self.targetDate.month)
        blanceSheet.genBalanceSheet()

        #更新收支表数据
        incomeStatement = IncomeStatement(self.targetDate.year, self.targetDate.month)
        incomeStatement.genIncomeStatement()

        QMessageBox.information(None,
                                '更新',
                                '本月记账报表数据更新全部完成',
                                QMessageBox.Yes)


    def onUpdateAllYearAllDate(self):
        '''
        函数功能：更新全年全部数据
        :return:
        '''

        pass

    def onClearCurVoucher(self):
        '''
        函数功能：清除当前的记账凭证
        :return:
        '''

        print ("clear_1")
        # 记账凭证摘要
        self.summary_textEdit.clear()
        # 记账凭证时间
        self.date_dateEdit.setDate(self.targetDate)

        # 资产增加
        self.property_increase_name_textEdit.clear()
        self.property_increase_value_lineEdit.clear()

        # 资产减少
        self.property_decrease_name_textEdit.clear()
        self.property_decrease_value_lineEdit.clear()

        # 权属增加
        self.ownership_increase_name_textEdit.clear()
        self.ownership_increase_value_lineEdit.clear()

        # 权属减少
        self.ownership_decrease_name_textEdit.clear()
        self.ownership_decrease_value_lineEdit.clear()

        self.add_pushButton.setText(initVoucherPage.ADD_BUTTON)

        logger.debug("clear_2")

    def onSelectPropertyIncreaseSub(self):
        '''
        函数功能：响应资产增加科目输入框点击事件
        :return:
        '''
        self.currentVoucherTextEdit = self.property_increase_name_textEdit
        self.showVoucherTreeInfo(ConfigManage.readConfig("PROPERTY_NAME_JSON"))

    def onSelectPropertyDecreaseSub(self):
        '''
        函数功能：响应资产减少科目输入框点击事件
        :return:
        '''

        self.currentVoucherTextEdit = self.property_decrease_name_textEdit
        self.showVoucherTreeInfo(ConfigManage.readConfig("PROPERTY_NAME_JSON"))

    def onSelectOwnershipIncreaseSub(self):
        '''
        函数功能：响应权属增加科目输入框点击事件
        :return:
        '''

        self.currentVoucherTextEdit = self.ownership_increase_name_textEdit
        self.showVoucherTreeInfo(ConfigManage.readConfig("OWNERSHIP_NAME_JSON"))


    def onSelectOwnershipDecreaseSub(self):
        '''
        函数功能：响应权属减少科目输入框点击事件
        :return:
        '''

        self.currentVoucherTextEdit = self.ownership_decrease_name_textEdit
        self.showVoucherTreeInfo(ConfigManage.readConfig("OWNERSHIP_NAME_JSON"))

    def onResizeRowsToContents(self):
        self.voucher_tableWidget.resizeRowsToContents()


    def onCustomMenu(self, pos):
        '''
        函数功能：表格右键展示菜单
        :param pos:
        :return:
        '''

        rowNum = -1

        for i in self.voucher_tableWidget.selectionModel().selection().indexes(): #这块实现的很奇怪
            rowNum = i.row()


        logger.debug("row_num=%d"%(rowNum))
        if (rowNum < 500 and rowNum >= 0): # 表格生效的行数，501行点击右键，不会弹出菜单
            menu = QMenu() #实例化菜单
            item1 = menu.addAction(u"修改")
            item2 = menu.addAction(u"删除")
            action = menu.exec_(self.voucher_tableWidget.mapToGlobal(pos))
        else:
            return

        if action == item1:
            logger.debug("修改记账凭证")
            self.modifyVoucherAccount(rowNum)
        elif action == item2:
            logger.debug("删除记账凭证")
            self.deleteVoucherAccount(rowNum)

    def updateVoucherTableData(self, threadCount):
        '''
        函数功能:响应更新表格数据的函数
        :param text:
        :return:
        '''

        logger.debug("call updateVoucherTableData function: index=%d" % (threadCount))

        self.voucher_tableWidget.update()

        for index in range(threadCount * initVoucherPage.ONE_THREAD_DATA, (threadCount + 1) * initVoucherPage.ONE_THREAD_DATA):

            if index >= len(self.accountVoucherResult):
                #没有数据了退出循环
                #数据查询工作完成
                logger.debug("search_pushButton.setEnabled(True)")
                self.search_pushButton.setEnabled(True)
                break

            voucherdataRow = self.accountVoucherResult[index]

            #序号
            noStr = "%d\t" % (index + 1)
            noItem = QTableWidgetItem(noStr)
            self.voucher_tableWidget.setItem(index, 0, noItem)

            #编号
            serialNumberStr = str(voucherdataRow.id)
            serialNumberItem = QTableWidgetItem(serialNumberStr)
            self.voucher_tableWidget.setItem(index, 1, serialNumberItem)

            # 摘要
            summaryItem = QTableWidgetItem(voucherdataRow.summary)
            self.voucher_tableWidget.setItem(index, 2, summaryItem)

            # 日期
            accountDateStr = str(voucherdataRow.account_date)
            accountDateItem = QTableWidgetItem(accountDateStr)
            self.voucher_tableWidget.setItem(index, 3, accountDateItem)

            # 金额
            if voucherdataRow.property_increase_value != 0:
                moneyValue = voucherdataRow.property_increase_value
            elif voucherdataRow.property_decrease_value != 0:
                moneyValue = voucherdataRow.property_decrease_value
            elif voucherdataRow.ownership_increase_value != 0:
                moneyValue = voucherdataRow.ownership_increase_value
            else:
                moneyValue = voucherdataRow.ownership_decrease_value

            moneyValueStr = xstring.dispose(toolkit.processValueSignificant(moneyValue)).humanized_amount(complex=True)
            moneyValueWiggetItem = QTableWidgetItem(moneyValueStr)
            self.voucher_tableWidget.setItem(index, 4, moneyValueWiggetItem)

            # 详情
            detailContext = ""
            if voucherdataRow.property_increase_name != "":
                if detailContext != "":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "资产增加：%s" % (voucherdataRow.property_increase_name)

            if voucherdataRow.property_decrease_name != "":
                if detailContext != "":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "资产减少：%s" % (voucherdataRow.property_decrease_name)

            if voucherdataRow.ownership_increase_name != "":
                if detailContext != "":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "权属增加：%s" % (voucherdataRow.ownership_increase_name)

            if voucherdataRow.ownership_decrease_name != "":
                if detailContext != "":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "权属减少：%s" % (voucherdataRow.ownership_decrease_name)

            detailContextWiggetItem = QTableWidgetItem(detailContext)
            self.voucher_tableWidget.setItem(index, 5, detailContextWiggetItem)

            self.voucher_tableWidget.update()

            if index == 0 or index == len(self.accountVoucherResult) - 1:
                self.voucher_tableWidget.resizeRowsToContents()  # 设置行宽自适应




class UpdateVoucherTableThread(QThread):
    '''
    类功能：用于展示记账凭证表数据时，进行异步线程更新。
    '''

    send_signal = pyqtSignal(int)

    def __init__(self, threadCount):
        super(UpdateVoucherTableThread, self).__init__()
        self.threadCount = threadCount


    def run(self):
        logger.debug("call UpdateVoucherTableThread class run function")




        for index in range(0, self.threadCount):

            self.send_signal.emit(index)
            logger.debug("更新thread! %d " % (index))

            UpdateVoucherTableThread.msleep(500)



